class Contato < ActiveRecord::Base

  belongs_to :municipio, :readonly => true

  validates_presence_of :municipio, :logradouro, :numero, :bairro, :cep

  # TODO DRY ou plugin
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :allow_nil => true

  # TODO DRY (acts_as_cep)
  def cep=(value)
    self[:cep] = value.gsub(/\D/, "")
  end

  # Helpers
  def formatted
    "#{logradouro}, nº #{numero}, #{bairro}, CEP #{formatted_cep}, #{municipio.formatted}"
  end

  def formatted_cep
    "#{cep[0,5]}-#{cep[5,3]}"
  end

  # dependent nullify
  def after_destroy
    PessoaJuridica.update_all("escritorio_id = NULL", ["escritorio_id = ?", self[:id]])
  end

end
